package com.oocl.sc.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.oocl.sc.dao.SuserDao;
import com.oocl.sc.entity.Suser;
import com.oocl.sc.util.DbUtil;

public class SuserDaoImpl implements SuserDao {

	public Suser login(String account, String password) {
		Suser suser = null;
		String sql = "select * from suser where account=? and password=?";
		Connection conn = null;
		PreparedStatement st = null;
		ResultSet rs = null;
		try {
			conn = DbUtil.getConnection();
			st = conn.prepareStatement(sql);
			st.setString(1, account);
			st.setString(2, password);
			rs = st.executeQuery();
			if(rs.next()){
				suser = new Suser();
				suser.setUsid(rs.getInt("usid"));
				suser.setAccount(rs.getString("account"));
				suser.setPassword(rs.getString("password"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.free(conn, st, rs);
		}
		return suser;
	}

	public int add(String account, String password) {
		String sql = "insert into suser(usid,account,password) values(suser_seq.Nextval,?,?)";
		Connection conn = null;
		PreparedStatement st = null;
		int m = 0;

		try {
			conn = DbUtil.getConnection();
			st = conn.prepareStatement(sql);
			st.setString(1, account);
			st.setString(2, password);
			m = st.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.free(conn, st, null);
		}
		return m;
	}

	public int isExisted(String account) {
		String sql = "select * from suser where account=?";
		Connection conn = null;
		PreparedStatement st = null;
		ResultSet rs = null;
		try {
			conn = DbUtil.getConnection();
			st = conn.prepareStatement(sql);
			st.setString(1, account);
			rs = st.executeQuery();
			if (rs.next()) {
				return 1;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.free(conn, st, rs);
		}
		return 0;
	}

}
